#include "MouseClick.h"
#include <iostream>

MouseClick* MouseClick::instance = new MouseClick(sf::Mouse::Button());

MouseClick* MouseClick::getInstance() {
    return instance;
}

MouseClick::MouseClick(sf::Mouse::Button aButton) : button(aButton) , pressed(false), tapped(false) {
    //  empty constructor
}

MouseClick::~MouseClick() {
    //  empty destructor
}

void MouseClick::update() {
    if(sf::Mouse::isButtonPressed(button)) {
        if(!pressed) {
            tapped = true;
            pressed = true;
        } else if(pressed) {
            tapped = false;
        }
    } else {
        tapped = false;
        pressed = false;
    }
}

void MouseClick::setKey(sf::Mouse::Button aButton) {
    button = aButton;
}

bool MouseClick::isPressed() {
    return pressed;
}

bool MouseClick::isTapped() {
    return tapped;
}

CollisionRay* MouseClick::rayCasting(sf::RenderWindow& window) {
    //Get mouse X, Y position relative within the window.
    sf::Vector2i mouse = sf::Mouse::getPosition(window);
    glm::vec3 clickPoint;
    clickPoint.x = (2.0f * mouse.x) / window.getSize().x - 1.0f;
    clickPoint.y = 1.0f - (2.0f * mouse.y) / window.getSize().y;
    clickPoint.z = 1.0f;

    glm::vec3 point = glm::vec3(glm::inverse(glm::mat4(Global::getCamera()->getProjection())) * glm::vec4(clickPoint, 1.0f));

    glm::vec3 direction = glm::normalize(glm::vec3(Global::getCamera()->getTransform() * glm::vec4(point, 0.0f)));
    glm::vec3 startPosition = glm::vec3(Global::getCamera()->getTransform() * glm::vec4(0.0f, 0.0f, 0.0f, 1.0f));

    return new CollisionRay(direction, startPosition);

    /*
    * SOURCE: http://www.antongerdelan.net/opengl/raycasting.html
    */
}
